package number_529;

public class Solution {
    public char[][] updateBoard(char[][] board, int[] click) {
        if (board[click[0]][click[1]] == 'M') {
            board[click[0]][click[1]] = 'X';
            return board;
        }
        dfs(board, click[0], click[1]);
        return board;
    }

    private void dfs(char[][] board, int row, int column) {
        if (row < 0 || row >= board.length || column < 0 || column >= board[0].length ||
                board[row][column] == 'B' || board[row][column] == 'M' ||
                Character.isDigit(board[row][column])) {
            return;
        }
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {-1, 1}, {-1, -1}, {1, -1}, {1, 1}};
        setBoxDigitOrB(board, dirs, row, column);
        if (Character.isDigit(board[row][column])) {
            return;
        }
        for (int[] dir : dirs) {
            dfs(board, row + dir[0], column + dir[1]);
        }
    }

    private void setBoxDigitOrB(char[][] board, int[][] dirs, int row, int column) {
        int bombNum = 0;
        for (int[] dir : dirs) {
            if (row + dir[0] < 0 || row + dir[0] >= board.length ||
                    column + dir[1] < 0 || column + dir[1] >= board[0].length) {
                continue;
            }
            int x = row + dir[0], y = column + dir[1];
            if (board[x][y] == 'M') {
                bombNum++;
            }
        }
        if (bombNum == 0) {
            board[row][column] = 'B';
        } else {
            board[row][column] = (char)(bombNum + '0');
        }
    }

    public static void main(String[] args) {
        System.out.println((char) 112);
        new Solution().updateBoard(new char[][]{
                {'E', 'E', 'E', 'E', 'E'},
                {'E', 'E', 'M', 'E', 'E'},
                {'E', 'E', 'E', 'E', 'E'},
                {'E', 'E', 'E', 'E', 'E'}
        }, new int[]{3, 0});
    }
}
